package com.huiminpay.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiminpay.common.cache.domain.PageVO;
import com.huiminpay.merchant.convert.MerchantConvert;
import com.huiminpay.merchant.convert.StoreConvert;
import com.huiminpay.merchant.dto.dto.MerchantDTO;
import com.huiminpay.merchant.dto.dto.StoreDTO;
import com.huiminpay.merchant.entity.Merchant;
import com.huiminpay.merchant.entity.Staff;
import com.huiminpay.merchant.entity.Store;
import com.huiminpay.merchant.entity.StoreStaff;
import com.huiminpay.merchant.mapper.MerchantMapper;
import com.huiminpay.merchant.mapper.StaffMapper;
import com.huiminpay.merchant.mapper.StoreMapper;
import com.huiminpay.merchant.mapper.StoreStaffMapper;
import com.huiminpay.merchant.service.IMerchantService;
import com.huiminpay.user.api.TenantService;
import com.huiminpay.user.api.dto.tenant.CreateTenantRequestDTO;
import com.huiminpay.user.api.dto.tenant.TenantDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
@Slf4j
public class MerchantServiceImpl implements IMerchantService {
    @Autowired
    MerchantMapper merchantMapper;
    @Autowired
    StoreMapper storeMapper;
    @Autowired
     StaffMapper staffMapper;
    @Autowired
    StoreStaffMapper storeStaffMapper;
    @Reference
    TenantService tenantService;


    public MerchantDTO findMchById(long id) {
        Merchant merchant = merchantMapper.selectById(id);
//        MerchantDTO merchantDto = new MerchantDTO();
//        BeanUtils.copyProperties(merchant,merchantDto);
        return MerchantConvert.INSTANCR.EntitydaoDTo(merchant);
    }

    @Override
    public MerchantDTO insertReg(MerchantDTO merchantDTO) {
//        Merchant merchant = new Merchant();
//        BeanUtils.copyProperties(merchantDTO,merchant);
        //手机号校验
        QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Merchant::getMobile,merchantDTO.getMobile());
        Integer integer = merchantMapper.selectCount(queryWrapper);
        if (integer>0){
            throw new RuntimeException("手机号已经存在");
        }

        //2创建租户账号初始化权限
        CreateTenantRequestDTO createAccountRequestDTO =new  CreateTenantRequestDTO();
        createAccountRequestDTO.setMobile(merchantDTO.getMobile());
        createAccountRequestDTO.setPassword(merchantDTO.getPassword());
        createAccountRequestDTO.setUsername(merchantDTO.getUsername());
        createAccountRequestDTO.setBundleCode("huimin-merchant");//初始化套餐编码
        createAccountRequestDTO.setTenantTypeCode("huimin-merchant");//商户类型
        createAccountRequestDTO.setName(merchantDTO.getUsername());
        TenantDTO tenantAndAccount = tenantService.createTenantAndAccount(createAccountRequestDTO);

        //3插入商户信息
        Merchant merchant = MerchantConvert.INSTANCR.DTodaoEntity(merchantDTO);
        merchant.setAuditStatus("0");//审核状态 0-未申请,1-已申请待审核,2-审核通过,3-审核拒绝
        merchant.setTenantId(tenantAndAccount.getId());//更新租户id
        merchantMapper.insert(merchant);
        //初始化店铺（根门店）
        Store store = new Store();
        store.setStoreName(merchantDTO.getUsername()+"001");
        store.setMerchantId(merchant.getId());
        store.setStoreStatus(true);
        store.setParentId(0L);

        storeMapper.insert(store);

        //添加员工
        Staff staff = new Staff();
        staff.setMerchantId(merchant.getId());
        staff.setUsername(merchantDTO.getUsername());
        staff.setMobile(merchantDTO.getMobile());
        staff.setStoreId(store.getId());
        staffMapper.insert(staff);
        //初始化门店和权限
         //给boss绑定门店管理员权限
        StoreStaff storeStaff = new StoreStaff();
        storeStaff.setStoreId(store.getId());
        storeStaff.setStaffId(staff.getId());
        storeStaffMapper.insert(storeStaff);


        merchantDTO.setId(merchant.getId());
        return merchantDTO;


    }

    @Override
    public MerchantDTO apply(MerchantDTO merchantDTO) {
//        Merchant merchant = new Merchant();
//        BeanUtils.copyProperties(merchantDTO,merchant);
        Merchant merchant = MerchantConvert.INSTANCR.DTodaoEntity(merchantDTO);

        //申请审核状态
        merchant.setAuditStatus("1");
        merchantMapper.updateById(merchant);
        //  merchantDTO.setAuditStatus("1");
        return MerchantConvert.INSTANCR.EntitydaoDTo(merchant);
    }

    @Override
    public MerchantDTO queryMerchantByTenantId(Long tenantId) {
        QueryWrapper<Merchant> qw = new QueryWrapper<>();
        qw.lambda().eq(Merchant::getTenantId,tenantId);
        Merchant merchant = merchantMapper.selectOne(qw);
        return MerchantConvert.INSTANCR.EntitydaoDTo(merchant);
    }

    @Override
    public PageVO<StoreDTO> queryStoreBypage(Integer pageNo, Integer pageSize, Long merchantId) {
      if (pageNo==null){
          pageNo=1;
      }
        Page<Store> page = new Page<>(pageNo,pageSize);
        QueryWrapper<Store> queryWrapper= new QueryWrapper<>();
        queryWrapper.lambda().eq(Store::getMerchantId,merchantId);
        //非空校验
        IPage<Store> storeIPage = storeMapper.selectPage(page, queryWrapper);
        List<Store> records = storeIPage.getRecords();
        PageVO<StoreDTO> pageVO= new PageVO<>();
        pageVO.setItems(StoreConvert.INSTANCE.listentity2dto(records));//分页数据
        pageVO.setPageSize(pageSize);
        pageVO.setPage(pageNo);
        pageVO.setCounts(storeIPage.getTotal());
        return pageVO;
    }

    @Override
    public StoreDTO selectStoreInfoById(Long storeId) {
        Store store = storeMapper.selectById(storeId);



        return StoreConvert.INSTANCE.entity2dto(store);
    }


//    /**
//     * 商户下 新增门店
//     *
//     * @param storeDTO
//     * @return com.huiminpay.merchant.api.dto.StoreDTO
//     * @author glls
//     * @date 2021/2/27 11:48
//     */
//
//    @Override
//    public StoreDTO createStore(StoreDTO storeDTO) throws BizException {
//        Store store = StoreConvert.INSTANCE.dto2entity(storeDTO);
//        log.info("商户下新增门店" + JSON.toJSONString(store));
//        storeMapper.insert(store);
//        return StoreConvert.INSTANCE.entity2dto(store);
//    }
//
//    /**
//     * 商户下 新增员工
//     * @param staffDTO
//     */
//    @Override
//    public StaffDTO createStaff(StaffDTO staffDTO) throws BizException {
//        //1.校验手机号格式及是否存在
//        String mobile = staffDTO.getMobile();
//        if(StringUtils.isBlank(mobile)){
//            throw new BizException(CommonErrorCode.E_100112);
//        }
//        //根据商户id和手机号校验唯一性
//        if(isExistStaffByMobile(mobile, staffDTO.getMerchantId())){
//            throw new BizException(CommonErrorCode.E_100113);
//        }
////2.校验用户名是否为空
//        String username = staffDTO.getUsername();
//        if(StringUtils.isBlank(username)){
//            throw new BizException(CommonErrorCode.E_100110);
//        }
////根据商户id和账号校验唯一性
//        if(isExistStaffByUserName(username, staffDTO.getMerchantId())){
//            throw new BizException(CommonErrorCode.E_100114);
//        }
//        Staff entity = StaffConvert.INSTANCE.dto2entity(staffDTO);
//        log.info("商户下新增员工");
//        staffMapper.insert(entity);
//        return StaffConvert.INSTANCE.entity2dto(entity);
//    }
//
//    /**
//     *  给门店设置管理员
//     * @author glls
//     * @param storeId 门店id
//     * @param staffId  员工id
//     * @return void
//     * @date 2021/2/27 13:00
//     */
//    @Override
//    public void bindStaffToStore(Long storeId, Long staffId) throws BizException {
//        StoreStaff storeStaff = new StoreStaff();
//        storeStaff.setStoreId(storeId);
//        storeStaff.setStaffId(staffId);
//        storeStaffMapper.insert(storeStaff);
//    }


    /**
     * 根据手机号判断员工是否已在指定商户存在
     * @param mobile 手机号
     * @return
     */
//    private boolean isExistStaffByMobile(String mobile, Long merchantId) {
//        LambdaQueryWrapper<Staff> lambdaQueryWrapper = new LambdaQueryWrapper<Staff>();
//        lambdaQueryWrapper.eq(Staff::getMobile, mobile).eq(Staff::getMerchantId, merchantId);
//        int i = staffMapper.selectCount(lambdaQueryWrapper);
//        return i > 0;
//    }
//
//    /**
//     * 根据账号判断员工是否已在指定商户存在
//     * @param userName
//     * @param merchantId
//     * @return
//     */
//    private boolean isExistStaffByUserName(String userName, Long merchantId) {
//        LambdaQueryWrapper<Staff> lambdaQueryWrapper = new LambdaQueryWrapper<Staff>();
//        lambdaQueryWrapper.eq(Staff::getUsername, userName).eq(Staff::getMerchantId,
//                merchantId);
//        int i = staffMapper.selectCount(lambdaQueryWrapper);
//        return i > 0;
//    }
}

//    @Override
//    public void insertReg(MerchantRegVo merchantRegVo) {
//
//    }

//    @Override
//    public MerchantDto findMchById(long id) {
//        Jedis jedis = new Jedis();
//        // 从redis中查询
//        Set<String> usernames = jedis.zrange("username", 0, -1);
////        List<MerchantDto> shangpuList = null;
//        MerchantDto merchantDto = new MerchantDto();
//        if (usernames == null || usernames.size() == 0) {
//            System.out.println("从mysql数据库中查询");
//            Merchant merchant = merchantMapper.selectById(id);
//            BeanUtils.copyProperties(merchant, merchantDto);
////            shangpuList.add(merchantDto);
//            HashMap<String, Double> map = new HashMap<>();
//            map.put(merchant.getAuditStatus(),1.0);
//            map.put(merchant.getBusinessLicensesImg(),2.0);
//            map.put(merchant.getContactsAddress(),3.0);
//            map.put(merchant.getIdCardAfterImg(),4.0);
//            map.put(merchant.getMerchantAddress(),5.0);
//            map.put(merchant.getMerchantName(),6.0);
//            map.put(merchant.getMerchantType(),7.0);
//            map.put(merchant.getUsername(),8.0);
//            jedis.zadd("username",map);
//
//        } else {
//            //查到数据返回
//            System.out.println("从redis中查");
//            for (String username : usernames) {
////                BeanUtils.copyProperties(shangpu1, merchantDto);
//                merchantDto.setUsername(username);
////                shangpuList.add(merchantDto);
//            }
//
//
//        }
//        return merchantDto;
//
//    }


      /*  Merchant merchant = merchantMapper.selectById(id);
        MerchantDto merchantDto = new MerchantDto();
        BeanUtils.copyProperties(merchant,merchantDto);
        return merchantDto;*/



